<template>
  <div>
    <DynamicTable header-title="回访满意度统计" :data-request="loadData" :search="true" :columns="columns" show-index
      bordered size="small" :pagination="false">
      <template #toolbar>
        <a-button type="primary" @click="aoaToExcel"> 导出 </a-button>
      </template>
    </DynamicTable>
  </div>
</template>

<script setup lang="tsx">
import type { TableColumn } from '@/components/core/dynamic-table';
import { useTable } from '@/components/core/dynamic-table';
import { satisfaction } from '@/api/workorder/statisticanalysis';
import { getDeptList } from '@/api/system/dept';
import { formatCategary2Tree, formatDept2Tree } from '@/core/permission/utils';
import { dictPotionsListApi } from '@/api/workorder/select';
import { getCategaryList } from '@/api/workorder/categary';
import { aoaToSheetXlsx } from '@/components/basic/excel';
import dayjs from 'dayjs';
import { ref } from 'vue';
import { selectDictLabel } from '@/utils/telchina';

defineOptions({
  name: 'throughput',
});
let tableData: any[] = [];
const workorderTypeData = ref([]);
const responsibleUnitDictData = ref([]);


const loadData = async (params) => {
  !params.startDate ? params.startDate = dayjs().subtract(7, 'days').format('YYYY-MM-DD') : ''
  !params.endDate ? params.endDate = dayjs().format('YYYY-MM-DD') : ''

  const data = await satisfaction(params);
  tableData = data;
  return data;
};

const [DynamicTable, dynamicTableInstance] = useTable({
  formProps: {
    fieldMapToTime: [
      ['acceptTime', ['startDate', 'endDate'], 'YYYY-MM-DD'],
    ],
    resetFunc: async () => {
      setTimeout(() => {
        dynamicTableInstance.queryFormRef?.setFieldsValue({ "acceptTime": [dayjs().subtract(7, 'days').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')] })
      }, 100);
    }
  }
});

getDeptList().then((res) => {
  responsibleUnitDictData.value = res.map((item) => ({
    label: item.name,
    value: item.id,
  }));
  dynamicTableInstance?.getQueryFormRef()?.updateSchema({
    field: `responsibleUnits`,
    componentProps: {
      treeData: formatDept2Tree(res),
    },
  });
})
getCategaryList({ "sysCode": 'workorder',  'visible': '0', 'categaryCode': 'industry_type' }).then((res) => {
  dynamicTableInstance?.getQueryFormRef()?.updateSchema({
    field: `industryTypes`,
    componentProps: {
      treeData: formatCategary2Tree(res, '0'),
    },
  });
});
// 自定义转码字典
dictPotionsListApi({ "code": 'workorder_type' }).then((res) => {
  workorderTypeData.value = res.map((item) => ({
    label: item.name,
    value: item.code,
  }));
  dynamicTableInstance?.getQueryFormRef()?.updateSchema({
    field: `workOrderTypes`,
    componentProps: {
      options: res.map((item) => ({
        label: item.name,
        value: item.code,
      }))
    },
  })
})


const aoaToExcel = () => {
  const colFilters = columns.filter((n) => n.dataIndex !== 'INDEX' && !n.hideInTable);
  const colFilterKeys = colFilters.map((n) => n.dataIndex);
  // 保证data顺序与header一致
  aoaToSheetXlsx({
    data: tableData
      .map((item) => {
        return colFilterKeys.reduce((p, k) => {
          p[k] = Array.isArray(item[k]) ? item[k].toString() : item[k];
          if(k == 'gdbl' ) {p[k] = item[k] + '%'; } 
          if(k == 'zrdw') {p[k] = selectDictLabel(responsibleUnitDictData.value, item[k]); }   
          if(k == 'gdlx') {p[k] = selectDictLabel(workorderTypeData.value, item[k]); }

          return p;
        }, {});
      })
      .map((item) => Object.values(item)),
    header: colFilters.map((column) => column.title),
    filename: '回访满意度统计.xlsx',
  });
};


const columns: TableColumn[] = [
  {
    title: '报表时间',
    key: 'acceptTime',
    dataIndex: 'acceptTime',
    align: 'center',
    width: '180px',
    hideInTable: true,
    formItemProps: {
      component: 'RangePicker',
      colProps: {
        span: 6,
      },
      componentProps: {
        showTime: false,
        defaultValue: [dayjs().subtract(7, 'days'), dayjs()],
        inputReadOnly: true,
        allowClear: false,
        ranges: {
          '今天': [dayjs(), dayjs()],
          '昨天': [dayjs().subtract(1, 'days'), dayjs().subtract(1, 'days')],
          '近一周': [dayjs().subtract(7, 'days'), dayjs()],
          '近两周': [dayjs().subtract(14, 'days'), dayjs()],
          '近一个月': [dayjs().subtract(30, 'days'), dayjs()],
          '近三个月': [dayjs().subtract(90, 'days'), dayjs()]
        }
      },
    },
  },
  {
    title: '行业类型',
    key: 'industryTypes',
    dataIndex: 'industryTypes',
    align: 'center',
    width: 120,
    hideInTable: true,
    formItemProps: {
      component: 'TreeSelect',
      colProps: {
        span: 6,
      },
      componentProps: {
        filterTreeNode: true,
        treeNodeFilterProp: 'name',
        treeDefaultExpandAll: true,
        multiple: true,
      }
    },
  },
  {
    title: '工单类型',
    key: 'workOrderTypes',
    dataIndex: 'workOrderTypes',
    width: 100,
    align: 'center',
    hideInTable: true,
    formItemProps: {
      colProps: {
        span: 6,
      },
      component: 'Select',
      componentProps: {
        mode: 'multiple',
      }
    },
  },
  {
    title: '责任单位',
    key: 'responsibleUnits',
    dataIndex: 'responsibleUnits',
    hideInTable: true,
    align: 'center',
    fixed: 'left',
    width: 100,
    formItemProps: {
      component: 'TreeSelect',
      colProps: {
        span: 6,
      },
      componentProps: {
        filterTreeNode: true,
        treeNodeFilterProp: 'name',
        treeDefaultExpandAll: true,
        multiple: true,
      }
    },
  },
  {
    title: '责任单位',
    dataIndex: 'zrdw',
    width: 200,
    align: 'center',
    fixed: 'left',
    hideInSearch: true,
    customCell: (record, rowIndex) => {
      return {
        rowSpan: mergeCells(record.zrdw, tableData, "zrdw", rowIndex)
      }
    },
    customRender: ({ record }) => {
      return selectDictLabel(responsibleUnitDictData.value, record.zrdw);
    },
  },
  {
    title: '工单类别',
    dataIndex: 'gdlx',
    width: 100,
    align: 'center',
    fixed: 'left',
    hideInSearch: true,
    customRender: ({ record }) => {
      return selectDictLabel(workorderTypeData.value, record.gdlx);
    },
  },
  {
    title: '工单总数',
    dataIndex: 'gdzs',
    width: 100,
    align: 'center',
    fixed: 'left',
    hideInSearch: true,
  },
  {
    title: '派单数',
    dataIndex: 'pds',
    width: 100,
    align: 'center',
    hideInSearch: true,
  },
  {
    title: '派单完成数',
    dataIndex: 'pdwcs',
    width: 100,
    align: 'center',
    hideInSearch: true,
  },
  {
    title: '仅过程不满意',
    dataIndex: 'jgcbmy',
    width: 100,
    align: 'center',
    hideInSearch: true,
  },
  {
    title: '仅结果不满意',
    dataIndex: 'jjgbmy',
    width: 100,
    align: 'center',
    hideInSearch: true,
  },
  {
    title: '均不满意',
    dataIndex: 'jbmy',
    width: 100,
    align: 'center',
    hideInSearch: true,
  },
  {
    title: '工单比例',
    dataIndex: 'gdbl',
    width: 100,
    align: 'center',
    hideInSearch: true,
    customRender: ({ record }) => {
      return record.gdbl + "%";
    },
  },
];

function mergeCells(text, data, key, index) {// 上一行该列数据是否一样
  if (index !== 0 && text === data[index - 1][key]) {
    return 0;
  }
  let rowSpan = 1;
  // 判断下一行是否相等
  for (let i = index + 1; i < data.length; i++) {
    if (text !== data[i][key]) {
      break;
    }
    rowSpan++;
  }
  return rowSpan;
}
</script>
<style lang="less">
.ant-input-number {
  width: 100%;
}

.workOrderNumber {
  color: #1890ff;
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.ant-tooltip-inner{
  width: 500px;
}
</style>